﻿using Humanizer;
using Kingdee.BOS.Util;
using LanDBom.Models;
using LanDBom.Models.Procure;
using MathNet.Numerics.Distributions;
using Microsoft.Office.Interop.Excel;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using OfficeOpenXml;
using Org.BouncyCastle.Math;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace LanDBom.Controllers
{
    public class ShenPIController : Controller
    {
        LDbaseEntities db = new LDbaseEntities();
        Bought bu = new Bought();
        Find_Libary Find_Libary = new Find_Libary();
        // GET: ShenPI
        public ActionResult Index(string bians, int stetede = 0, string Namesed = "", string liyou = "", string Njism = "", string Name1 = "")
        {
            Njism = Njism == "S" ? "核价审批" : Njism == "G" ? "供应商审核" : "对外报价";
            var AA = db.Informa.Where(s => s.Inf_shen == bians).ToList();
            var APP = db.Applications.Where(s => s.AP_bian == bians).ToList();
            var ABP = db.shenpingliu.Where(s => s.FJINF == bians && s.FMIao == Njism).FirstOrDefault();
            var ABC = ABP.FShenR;
            ViewBag.AASHEN = AA;
            ViewBag.APPSH = APP;
            Session["jisn"] = ABC;
            if (stetede == 1)
            {
                string message = "";
                //判断是否符合审批条件
                int index = 0;
                int temp = 0;
                int num = int.Parse(db.shenpingliu.Where(x => x.FJINF == bians).FirstOrDefault().FSHENP.ToString());//buzho
                if (ABP.FFZ != "通过")
                {
                    ABP.FFZ = "通过";
                    index = 1;
                }
                else
                if (ABP.FTZ != "通过")
                {
                    ABP.FTZ = "通过";
                    index = 2;
                }
                else
                {
                    ABP.FTTZ = "通过";
                    index = 3;
                }
                if (index == num)
                {
                    if (Njism == "供应商审核")
                    {
                        var shu = db.Providers.Where(s => s.PR_bian == bians).FirstOrDefault();
                        shu.PR_bei = "临时";
                        db.Entry(shu).State = EntityState.Modified;
                        temp = db.SaveChanges();
                        message = temp > 0 ? "审批成功" : "审批失败";
                    }
                    else
                    {
                        Applications applications = db.Applications.Where(x => x.AP_bian == bians).FirstOrDefault();
                        //判断工艺是否做完
                        var BOMS = db.BOMini.Where(s => s.BOM2_bian == bians && s.BOM2_Zhuang == applications.App_BanB).ToList();
                        var shunLM = 0;
                        foreach (var item in BOMS)
                        {
                            if (item.BOM2_GY == "" || item.BOM2_GY == null)
                            {
                                shunLM++;
                            }
                        }
                        if (shunLM == 0)
                        {
                            ABP.Fzhuang = "结束";
                            int qinji = db.SaveChanges();
                            applications.App_bu = "6";
                            db.Entry(applications).State = EntityState.Modified;
                            temp = db.SaveChanges();
                            string SHiji = bu.Levesjin(bians);
                            if (SHiji == "Y")
                            {
                                //执行物料记录程序
                                bu.WLGX(bians);
                            }
                            message = temp > 0 ? "审批成功" : "审批失败";
                        }
                        else
                        {
                            message = "审核通过 有自制物料未做工艺请通知对应业务";
                        }
                    }
                }
                else
                {
                    int shinfko = db.SaveChanges();
                    message = shinfko > 0 ? "审批成功" : "审批失败";
                }
                return Content(message);
            }
            if (stetede == 2)
            {
                string message = "";
                string KMji = "";
                //判断是否符合审批条件
                if (ABP.FFirst == Namesed && ABP.FFZ == "审批中")
                {
                    ABP.FFZ = "驳回";
                    KMji = "N";
                }
                if (ABP.FFZ == "通过" && ABP.FTwo == Namesed && ABP.FTZ == "审批中")
                {
                    ABP.FTZ = "驳回"; KMji = "N";
                }
                if (ABP.FFZ == "通过" && ABP.FTZ == "通过" && ABP.FThree == Namesed && ABP.FTTZ == "审批中")
                {
                    ABP.FTTZ = "驳回"; KMji = "N";
                }
                if (KMji == "")
                {
                    message = "上一级人员未审批或已审批通过，请等待";
                    return Json(message);
                }

                ABP.Fliy = liyou;
                ABP.Fzhuang = "驳回";
                ABP.FFIZ = Name1;
                db.Entry(ABP).State = EntityState.Modified;
                int shinfko = db.SaveChanges();

                int da = 0;
                if (shinfko > 0)
                {
                    var shuan = db.Applications.Where(s => s.AP_bian == bians).FirstOrDefault();
                    var shinf = double.Parse(shuan.App_BanB);
                    var shifn = Math.Truncate(shinf) + 1;
                    shuan.App_BanB = shifn.ToString();
                    shuan.App_bu = "5";
                    shuan.APP_liy = liyou;
                    shuan.APP_shr = Name1;
                    db.Entry(shuan).State = EntityState.Modified;
                    int sun = db.SaveChanges();
                    int font = 0;
                    if (sun > 0)
                    {
                        var BOmi = db.BOMini.Where(b => b.BOM2_bian == bians && b.BOM2_Zhuang == shinf.ToString()).ToList();
                        foreach (var b in BOmi)
                        {
                            b.BOM2_Zhuang = shifn.ToString();
                            if (b.BOM2_sunhao == "已核价")
                            {
                                b.BOM2_sunhao = "已询价";
                            }
                            db.Entry(b).State = EntityState.Modified;
                            font += db.SaveChanges();
                        }
                        //添加驳回理有

                        var bohui = new BeiZhu()
                        {
                            B_Bian = bians,
                            B_bei = liyou,
                            B_Date = DateTime.Now.ToString("yyyy/M/d"),
                            B_BR = Name1,
                        };
                        db.BeiZhu.Add(bohui);
                        int IJK = db.SaveChanges();

                        var inf = db.Informa.Where(s => s.Inf_shen == bians).ToList();
                        foreach (var item in inf)
                        {
                            item.Inf_zhuang = "已提交";
                            db.Entry(item).State = EntityState.Modified;
                            int hunns = db.SaveChanges();
                        }
                        message = sun > 0 ? "驳回通过" : "驳回未通过";
                    }
                }
                return Content(message);
            }
            if (stetede == 3)
            {
                //判断审批人数是否符合要求符合要求infrom表审批中改为等待中
                var SHEN = db.shenpingliu.Where(s => s.FJINF == bians).FirstOrDefault();
                var KOMFND = db.Informa.Where(s => s.Inf_shen == bians && s.Inf_zhuang != "已提交").ToList();
                var IndE = "审批中";
                if (SHEN.FSHENP == 1)
                {
                    if (SHEN.FFZ == "通过")
                    {
                        IndE = "等待中";
                    }
                }
                if (SHEN.FSHENP == 2)
                {
                    if (SHEN.FFZ == "通过" && SHEN.FTZ == "通过")
                    {
                        IndE = "等待中";
                    }
                }
                if (SHEN.FSHENP == 3)
                {
                    if (SHEN.FFZ == "通过" && SHEN.FTZ == "通过" && SHEN.FTTZ == "通过")
                    {
                        IndE = "等待中";
                    }
                }
                string mesage = "";
                if (IndE == "审批中")
                {
                    mesage = "还有人未审批";
                }
                else
                {
                    foreach (var item in KOMFND)
                    {
                        item.Inf_zhuang = IndE;
                        db.Entry(item).State = EntityState.Modified;
                    }
                    int da = db.SaveChanges();
                    mesage = da > 0 ? "审批结束" : "还有人未审批";
                }

                return Json(mesage);
            }
            if (stetede == 4)
            {
                string message = "";
                string KMji = "";
                //判断是否符合审批条件
                if (ABP.FFirst == Namesed && ABP.FFZ == "审批中")
                {
                    ABP.FFZ = "驳回";
                    KMji = "N";
                }
                if (ABP.FFZ == "通过" && ABP.FTwo == Namesed && ABP.FTZ == "审批中")
                {
                    ABP.FTZ = "驳回"; KMji = "N";
                }
                if (ABP.FFZ == "通过" && ABP.FTZ == "通过" && ABP.FThree == Namesed && ABP.FTTZ == "审批中")
                {
                    ABP.FTTZ = "驳回"; KMji = "N";
                }
                if (KMji == "")
                {
                    message = "上一级人员未审批或已审批通过，请等待";
                    return Json(message);
                }
                ABP.Fliy = liyou;
                db.Entry(ABP).State = EntityState.Modified;
                int shinfko = db.SaveChanges();
                if (shinfko > 0)
                {
                    //询价和核价审批驳回 记录删除
                    var APPeds = db.Applications.FirstOrDefault(s => s.AP_bian == bians);
                    APPeds.App_bu = "6";
                    db.Entry(APPeds).State = EntityState.Modified;
                    int jisn = db.SaveChanges();
                    message = jisn > 0 ? "驳回通过" : "驳回失败";
                }
                return Content(message);
            }
            if (stetede == 5)
            {
                string message = "";
                //判断是否符合审批条件
                int index = 0;
                int temp = 0;
                int num = int.Parse(db.shenpingliu.Where(x => x.FJINF == bians).FirstOrDefault().FSHENP.ToString());
                if (ABP.FFZ != "通过")
                {
                    ABP.FFZ = "通过";
                    index = 1;
                }
                else if (ABP.FTZ != "通过" && ABP.FTZ != "" && ABP.FTZ != null)
                {
                    ABP.FTZ = "通过";
                    index = 2;
                }
                if (ABP.FTTZ == "通过")
                {
                    ABP.FTTZ = "通过";
                    index = 3;
                }
                if (index == num)
                {
                    ABP.Fzhuang = "结束";
                    Applications applications = db.Applications.Where(x => x.AP_bian == bians).FirstOrDefault();
                    applications.App_bu = "7";
                    int qinji = db.SaveChanges();
                    if (qinji == 1)
                    {
                        temp = 1;
                    }
                }
                db.Entry(ABP).State = EntityState.Modified;
                int shinfko = db.SaveChanges();
                message = shinfko > 0 ? "审批通过" : "审批失败";
                if (temp == 1)
                {
                    message = "审批结束";
                }
                return Content(message);
            }
            return View();
        }
        //public ActionResult Shenjinbu(string bians, int stetede = 0, string Namesed = "")
        //{
        //    if (stetede == 3)
        //    {
        //        //判断审批人数是否符合要求符合要求infrom表审批中改为等待中
        //        var SHEN = db.shenpingliu.Where(s => s.FJINF == bians).FirstOrDefault();
        //        var KOMFND = db.Informa.Where(s => s.Inf_shen == bians).ToList();
        //        var IndE = "";
        //        if (SHEN.FSHENP == 1)
        //        {
        //            if (SHEN.FFZ == "通过")
        //            {
        //                IndE = "等待中";
        //            }
        //        }
        //        if (SHEN.FSHENP == 2)
        //        {
        //            if (SHEN.FFZ == "通过" && SHEN.FTZ == "通过")
        //            {
        //                IndE = "等待中";
        //            }
        //        }
        //        if (SHEN.FSHENP == 3)
        //        {
        //            if (SHEN.FFZ == "通过" && SHEN.FTZ == "通过" && SHEN.FTTZ == "通过")
        //            {
        //                IndE = "等待中";
        //            }
        //        }
        //        foreach (var item in KOMFND)
        //        {
        //            db.Entry(item).State = EntityState.Modified;
        //        }
        //        int da = db.SaveChanges();
        //        string mesage = da > 0 ? "审批结束" : "还有人未审批";
        //        return Content(mesage);
        //    }
        //    return View();
        //}

        public ActionResult HJSP(string bians, int state = 0, string Bians = "")
        {
            var listINF = db.Informa.Where(x => x.Inf_shen == bians).ToList();
            ViewBag.APPH = db.Applications.Where(s => s.AP_bian == bians).ToList();
            if (bians != null)
            {
                Session["bians"] = bians;
            }
            if (state == 1)
            {
                var listapp = db.Applications.Where(x => x.AP_bian == bians).ToList();
                var temp = from a in listapp
                           select new { a.App_Kehu, a.AP_bian, a.App_qishi, a.App_JTime };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 2)
            {
                var listBOM = db.BOMini.Where(s => s.BOM2_bian == bians && s.BOM2_Lei == "外购").ToList();
                var temp = from a in listINF
                           join b in listBOM on a.Inf_wu equals b.BOM2_wuLiu into c
                           from d in c.DefaultIfEmpty()
                           select new { a.Inf_wu, a.Inf_gong, d.BOM2_mioa, Inf_huiP = a == null ? "0" : a.Inf_huiP, a.Inf_JT };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 3)
            {
                var ddd = DependencyResolver.Current.GetService<ProcureController>();
                var spp = db.Applications.Where(s => s.AP_bian == bians).FirstOrDefault().App_BanB.ToString();
                var bomjins = db.BOMini.Where(s => s.BOM2_bian == bians && s.BOM2_Zhuang == spp).ToList();
                var shunKKm = "";
                foreach (var item in bomjins)
                {
                    var ingf = item.BOM2_id;
                    var shun = db.Informa.Where(s => s.BOM2_id == ingf && s.Inf_shen == bians).ToList();
                    if (shun.Count() <= 0)
                    {
                        continue;
                    }
                    System.Data.DataTable dt = ddd.XUNTbale(ingf, shun);
                    shunKKm += ConvertToHtml(dt, ingf);
                }
                return Content(shunKKm);
            }
            else if (state == 4)
            {
                try
                {
                    //完成事件
                    var SHEN = db.shenpingliu.Where(s => s.FJINF == Bians).FirstOrDefault();
                    var KOMFND = db.Informa.Where(s => s.Inf_shen == Bians).ToList();
                    var IndE = "审批中";
                    if (SHEN.FSHENP == 1)
                    {
                        if (SHEN.FFZ == "通过")
                        {
                            IndE = "审批成功";
                        }
                    }
                    if (SHEN.FSHENP == 2)
                    {
                        if (SHEN.FFZ == "通过" && SHEN.FTZ == "通过")
                        {
                            IndE = "审批成功";
                        }
                    }
                    if (SHEN.FSHENP == 3)
                    {
                        if (SHEN.FFZ == "通过" && SHEN.FTZ == "通过" && SHEN.FTTZ == "通过")
                        {
                            IndE = "审批成功";
                        }
                    }
                    string mesage = "";
                    if (IndE == "审批中")
                    {
                        mesage = "还有人未审批，不能完成";
                    }
                    else
                    {
                        var Informatica = db.Informa.Where(s => s.Inf_shen == Bians && s.Inf_zhuang == "已确认").ToList();
                        if (Informatica.Count > 1)
                        {
                            Informatica = Informatica.GroupBy(d => new { d.Inf_wu }).Select(a => a.OrderBy(b => b.Inf_huiP).ElementAt(0)).ToList();//当确定的供应商又时获取最小值
                        }
                        foreach (var item in Informatica)
                        {
                            var DDD = item.Inf_wu;//供应商回价的物料
                            var GON = item.Inf_gong;//供应商
                            var PRice = item.Inf_huiP;//回价价格
                                                      //找到物料并替换
                            var Nammd = db.Ndardo.FirstOrDefault(s => s.Nd_wuLiao == DDD);//先保存后修改
                            if (Nammd == null)
                            {
                                var shundf = db.BOMini.Where(a => a.BOM2_wuLiu == DDD).FirstOrDefault();
                                var sjinf = DateTime.Now.Date.ToString("yyyy-MM-dd");
                                var jnsgd = shundf.BOM2_liao;//料号
                                Ndardo ndardo = new Ndardo();
                                ndardo.Nd_wuLiao = DDD;
                                ndardo.Nd_jiage = (decimal?)double.Parse(PRice);
                                ndardo.Nd_danwei = shundf.BOM2_fenzi;
                                ndardo.Nd_shengxiao = sjinf.ToString();
                                ndardo.Nd_wuLiao = DDD;
                                ndardo.Nd_Gong = GON;
                                db.Ndardo.Add(ndardo);
                            }
                            else
                            {
                                Nammd.Nd_Gong = GON;
                                db.Entry(Nammd).State = EntityState.Modified;
                            }

                            int shid = db.SaveChanges();//当保存的供应商之后添加价格到BOM中
                            if (shid > 0)
                            {
                                var ikms = item.BOM2_id;
                                var BO = db.BOMini.FirstOrDefault(s => s.BOM2_id == ikms);
                                BO.BOM2_mioa = PRice;
                                db.Entry(Nammd).State = EntityState.Modified;
                                int KONND = db.SaveChanges();
                                var APPeds = db.Applications.FirstOrDefault(s => s.AP_bian == bians);
                                APPeds.App_bu = "6";
                                db.Entry(APPeds).State = EntityState.Modified;
                                int jisn = db.SaveChanges();
                                mesage = jisn > 0 && KONND > 0 ? "申批完成" : "完成故障";
                            }
                        }
                    }
                    return Json(mesage);
                }
                catch (Exception ex)
                {
                    return Json(ex.Message);
                }
            }
            else if (state == 5)
            {
                var list = db.BOMini.Where(x => x.BOM2_bian == Bians).ToList();

                var temp = from a in list
                           select new { a.BOM2_id, a.BOM2_Lei, a.BOM2_wuLiu, a.BOM2_liao, a.BOM2_Sone, a.BOM2_ST, a.BOM2_Guige, a.BOM2_chen };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");

            }
            else if (state == 6)
            {
                var pridss = db.ProcessRecord.Where(x => x.wl_liao == Bians).FirstOrDefault();
                var prid = pridss == null ? -222 : pridss.prr_id;

                if (prid == -222)
                {
                    return Content("该行不存在");
                }
                var list = db.CraftMaterials.Include("parice").Where(x => x.prr_id == prid).ToList();

                var temp = from a in list
                           select new { a.prrw_guige, a.prrw_shu, a.prrw_jia, PA_ZhongL = a.parice == null ? "" : a.parice.PA_ZhongL };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 7)
            {
                var pridss = db.ProcessRecord.Where(x => x.wl_liao == Bians).FirstOrDefault();
                var prid = pridss == null ? -222 : pridss.prr_id;

                if (prid == -222)
                {
                    return Content("该行不存在");
                }
                var list = db.ProcessFlow.Include("libray").Where(x => x.prr_id == prid).ToList();

                var temp = from a in list
                           select new { a.pfw_jia, a.pfw_gg, a.CL_beizhu, LB_fne = a.libray == null ? "" : a.libray.LB_fne };
                JsonSerializerSettings settings = new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    Formatting = Formatting.Indented
                };
                string jsongStr = JsonConvert.SerializeObject(temp, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }

        public ActionResult Gys_Pj(string bian = null, int state = 0, int por_id = 0)
        {
            Session["bian"] = bian;
            if (state == 1)
            {
                var list = db.Providers.Where(x => x.PR_bian == bian).ToList();
                int number = 0;
                foreach (Providers providers in list)
                {
                    number = providers.PR_ID;
                }
                var list2 = db.flow.Where(s => s.pr_id == number).ToList();
                var result = from c in list
                             join o in list2 on c.PR_ID equals o.pr_id
                             select new { c.PR_ID, c.PR_name, c.PR_hang, c.PR_gswz, c.PR_you, c.PR_lxr, c.PR_lxrsj, o.fl_clsj, o.fl_cfmj, o.fl_zrs, o.fl_turnover1, o.fl_turnover2, o.fl_turnover3 };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(result, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 2)
            {
                string temp = db.evaluate.Count().ToString();
                return Json(temp);
            }
            else if (state == 3)
            {
                Providers providers = db.Providers.Where(x => x.PR_bian == bian).FirstOrDefault();
                providers.PR_bei = "准入";
                int temp = db.SaveChanges();
                string mesage = temp > 0 ? "审批完成" : "错误";
                return Content(mesage, "application/json");
            }
            else if (state == 4)
            {
                var list = db.evaluate.Where(x => x.por_id == por_id).ToList();
                var result = from a in list
                             select new { a.eva_cpxy, a.eva_cpxy_s, a.eva_cpzl, a.eva_cpzl_s, a.eva_jgsp, a.eva_jgsp_s, a.eva_jsnl, a.eva_jsnl_s, a.eva_scnl, a.eva_scnl_s, a.eva_ypqk, a.eva_ypqk_s, a.eva_zltx, a.eva_zltx_s, a.eva_bh, a.eva_bz, a.eva_pdry, a.eca_pdrq, a.eva_pz, a.eva_pzrq, a.eva_xmpz, a.eva_xmrq, a.eva_shrq, a.eva_shry };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(result, settings);
                return Content(jsongStr, "application/json");
            }
            else if (state == 5)
            {
                var list = db.Zl.Where(x => x.pro_id == por_id).ToList();
                var result = from a in list
                             select new { a.zz_ISO9000, a.zz_ISO14001, a.zz_OHSAS18001, a.zz_jq, a.zz_lb, a.zz_ROHS, a.zz_qt, a.zz_yzzz, a.zz_swdjz, a.zz_ghxy, a.zz_NDA, a.zz_yhwz, a.zz_gsjs };
                JsonSerializerSettings settings = new JsonSerializerSettings();
                string jsongStr = JsonConvert.SerializeObject(result, settings);
                return Content(jsongStr, "application/json");
            }
            return View();
        }

        public ActionResult addlxx(List<evaluate> flows)
        {
            foreach (evaluate flow in flows)
            {
                db.evaluate.Add(flow);
                int temp = db.SaveChanges();
                string powasd = temp > 0 ? "添加成功" : "添加失败";
                return Json(powasd);
            }
            return View();
        }
        public ActionResult addzl(List<Zl> flows)
        {
            foreach (Zl flow in flows)
            {
                db.Zl.Add(flow);
                int temp = db.SaveChanges();
                string powasd = temp > 0 ? "添加成功" : "添加失败";
                return Json(powasd);
            }
            return View();
        }
        public ActionResult changesp(List<evaluate> flows)
        {
            foreach (evaluate flow in flows)
            {
                evaluate evaluate = db.evaluate.Where(x => x.eva_bh == flow.eva_bh).FirstOrDefault();
                evaluate.eva_shrq = flow.eva_shrq;
                evaluate.eva_shry = flow.eva_shry;
                evaluate.eva_xmpz = flow.eva_xmpz;
                evaluate.eva_xmrq = flow.eva_xmrq;
                evaluate.eva_zhuang = flow.eva_zhuang;
                int temp = db.SaveChanges();
                string powasd = temp > 0 ? "添加成功" : "添加失败";
                return Json(powasd);
            }
            return View();
        }
        public ActionResult Duiw(string bians, int state = 0, string Njism = "")
        {
            ViewBag.APPH = db.Applications.Where(s => s.AP_bian == bians).ToList();
            var ABP = db.shenpingliu.Where(s => s.FJINF == bians && s.FMIao == Njism).FirstOrDefault();
            var ABC = ABP.FShenR;
            Session["jisned"] = ABC;
            if (state == 1)
            {
                try
                {
                    var app = db.Applications.Where(s => s.AP_bian == bians).FirstOrDefault();
                    var shunnd = app.App_BanB;
                    //bomin
                    var bomi = db.BOMini.Where(s => s.BOM2_bian == bians && s.BOM2_Zhuang == shunnd).ToList();
                    var shunf = new List<Informa>();
                    foreach (var item in bomi)
                    {
                        var shunnf = item.BOM2_CB.Split(',');
                        for (int i = 0; i < shunnf.Length; i++)
                        {
                            var sunf = shunnf[i].Split(':');
                            if (sunf.Length > 1)
                            {
                                var jiee = "";
                                var Liao = item.BOM2_liao;
                                var hu = db.Formation.Where(J => J.FM_bai == Liao).FirstOrDefault();
                                if (hu == null)
                                {
                                    jiee = "1";
                                }
                                else
                                {
                                    var sh = hu.FM_Jieti.Split(',');
                                    jiee = sh[i];
                                }
                                //存在供应商
                                if (sunf[0] != "" && sunf[0] != "0")
                                {
                                    var ji = int.Parse(sunf[0]);
                                    var INF = db.Informa.Where(s => s.Inf_id == ji).FirstOrDefault();
                                    var INFHUD = new Informa()
                                    {
                                        BOM2_id = item.BOM2_id,
                                        Inf_wu = item.BOM2_wuLiu,
                                        Inf_liao = item.BOM2_liao,
                                        Inf_gong = INF.Inf_gong,
                                        Inf_JT = sunf[1],
                                        Inf_miao = item.BOM2_ST,
                                        Inf_huiP = sunf[2],
                                    };
                                    shunf.Add(INFHUD);
                                }
                                else
                                {

                                    //不存在供应商
                                    var INFHUD = new Informa()
                                    {
                                        BOM2_id = item.BOM2_id,
                                        Inf_wu = item.BOM2_wuLiu,
                                        Inf_liao = item.BOM2_liao,
                                        Inf_gong = "",
                                        Inf_JT = sunf.Length <= 1 ? jiee : sunf[1],
                                        Inf_miao = item.BOM2_ST,
                                        Inf_huiP = sunf.Length <= 1 ? sunf[0] : sunf[2],
                                    };
                                    shunf.Add(INFHUD);
                                }
                            }
                        }

                        var miao = item.BOM2_mioa?.Split(',');
                        for (int i = 0; i < miao.Length; i++)
                        {
                            var M = miao[i].Split(':');
                            if (M.Length > 1)
                            {
                                var EV = shunf.Where(s => s.BOM2_id == item.BOM2_id && s.Inf_JT == M[0]).FirstOrDefault();
                                if (EV != null)
                                {
                                    EV.Inf_LI = M[1];
                                }
                            }
                            else if (M.Length == 1 && M[0] != "")
                            {
                                var EV = shunf.Where(s => s.BOM2_id == item.BOM2_id).ToList();
                                foreach (var DE in EV)
                                {
                                    DE.Inf_LI = EV == null ? "" : M[0];
                                }
                            }
                        }
                        if (item.BOM2_Jin != null && item.BOM2_Jin != "")
                        {
                            var JINK = item.BOM2_Jin.Split(',');
                            for (int i = 0; i < JINK.Length; i++)
                            {
                                var K = JINK[i].Split(':');
                                if (K.Length > 1)
                                {
                                    var EV = shunf.Where(s => s.BOM2_id == item.BOM2_id && s.Inf_JT == K[0]).FirstOrDefault();
                                    if (EV != null)
                                    {
                                        EV.Inf_LIs = K[1];
                                    }
                                }
                                else if (K.Length == 1 && K[0] != "")
                                {
                                    var EV = shunf.Where(s => s.BOM2_id == item.BOM2_id).ToList();
                                    foreach (var DE in EV)
                                    {
                                        DE.Inf_LIs = K[0];
                                    }
                                }
                            }
                        }
                    }
                    var sijnd = from a in shunf
                                select new { a.Inf_wu, BOM2_ST = a.Inf_miao, a.Inf_id, a.Inf_huiP, OP_LR = a.Inf_LIs, a.Inf_JT, a.Inf_gong, BOM2_CB = a.Inf_huiP, a.Inf_LI, a.BOM2_id };
                    JsonSerializerSettings settings = new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // 处理循环引用  
                        Formatting = Formatting.Indented // 格式化输出，便于阅读  
                    };
                    string jsongStr = JsonConvert.SerializeObject(sijnd, settings);
                    return Content(jsongStr, "application/json");
                }
                catch (Exception ex)
                {
                    var shun=ex.Message;
                }

            }
            return View();
        }
        public static int sjindd;
        public static string ConvertToHtml(System.Data.DataTable table, int AAA)
        {
            LDbaseEntities LD = new LDbaseEntities();
            var BOM = LD.BOMini.Find(AAA).BOM2_wuLiu;
            var BOMBBB = LD.BOMini.Find(AAA).BOM2_bei;
            var Bian = LD.BOMini.Find(AAA).BOM2_bian;
            var html = new StringBuilder();
            // 添加表格开始标签  
            html.AppendLine("<table border='1' class='table tab' id='HSJI_KO'>");
            //添加标体
            html.AppendLine("<tr>");
            html.AppendFormat("<th colspan='1' class='HJ_CP_WLM'style='font-size:20px;'>{0}</th>", BOM);
            if (BOMBBB != null)
            {
                html.AppendFormat("<th colspan='1' class='HJ_CP_WLM'>推荐备注:  <span style='text-align:left'>{0}</span></th>", BOMBBB);
            }
            //var JHN = LD.Informa.Where(s => s.BOM2_id == AAA && s.Inf_shen == Bian).Distinct().ToList();
            var shunnd = AAA.ToString();
            html.AppendLine("</tr>");
            // 添加表头  
            html.AppendLine("<tr>");
            foreach (DataColumn column in table.Columns)
            {
                html.AppendFormat("<th>{0}</th>", column.ColumnName);
            }
            html.AppendLine("</tr>");
            var husn = "his";
            Random random = new Random();
            var inji = 0;
            // 添加表格数据
            foreach (DataRow row in table.Rows)
            {
                inji++;
                int sji = random.Next(100, 1000);
                if (sjindd == sji)
                {
                    sji = random.Next(100, 1000);
                }
                husn += sji;
                html.AppendLine("<tr>");
                var sun = 0;
                foreach (DataColumn column in table.Columns)
                {
                    sun++;
                    if (sun > 2)
                    {
                        var shuund = row[column].ToString();
                        var s = shuund.Split(';');
                        var LLL = int.Parse(s[0]);
                        var JJNNFF = LD.Informa.FirstOrDefault(d => d.Inf_id == LLL);
                        if (JJNNFF.Inf_zhuang.ToString() == "已确认")
                        {
                            html.AppendFormat("<td style='text-align:left'><lable style='width:30px;'>{0}</lable><input type='radio' name='{1}' checked/><span style='display:none' name='HJ_CP_i_x1'>{2}</span></td>", s[s.Length - 1], husn, s[0]);
                        }
                        else
                        {
                            html.AppendFormat("<td style='text-align:left'><lable style='width:30px;'>{0}</lable><input type='radio' name='{1}'/><span style='display:none' name='HJ_CP_i_x1'>{2}</span></td>", s[s.Length - 1], husn, s[0]);
                        }

                    }
                    else
                    {
                        html.AppendFormat("<td style='text-align:left'>{0}</td>", row[column]);
                    }

                }
                html.AppendLine("</tr>");
                sjindd = sji;
            }
            var Bomde = LD.BOMin.Where(s => s.App_bian == Bian && s.Bom_chen != null && (s.BOM_guige == "0" || s.BOM_guige == null)).ToList();//不足三个供应商备注记录
            var InforCount = LD.Informa.Where(s => s.Inf_shen == Bian && s.BOM2_id == AAA).GroupBy(s => new { s.Inf_gong }).Select(s => new { Igong = s.Key }).ToList().Count();//供应商询价是否大于等于3个
            html.AppendLine("<tr>");
            if (Bomde.Count() > 0)
            {
                for (int i = Bomde.Count() - 1; i < Bomde.Count(); i++)
                {
                    var BN = Bomde == null ? "" : Bomde[i].Bom_chen;
                    if (BN != "" && InforCount < 3)
                    {
                        html.AppendFormat("<td colspan='3' class='HJ_CP_WLM'>供应商少于三个的备注:  <span style='text-align:left'>{0}</span></td>", BN);
                        break;
                    }
                }
            }
            var infd = LD.BOMin.Where(s => s.App_bian == Bian && s.Bom_chen != null && s.BOM_guige == "1" && s.BOM_name == shunnd).ToList();//最优推荐
            //最优推荐
            //低于理论价格10%理由
            var infd1 = LD.BOMin.Where(s => s.App_bian == Bian && s.Bom_chen != null && s.BOM_guige == "2" && s.BOM_name == shunnd).ToList();//最优推荐
            if (infd1.Count() > 0)
            {
                for (int i = infd1.Count() - 1; i < infd1.Count(); i++)
                {
                    var BN = infd1 == null ? "" : infd1[i].Bom_chen;
                    if (BN != "")
                    {
                        html.AppendFormat("<td colspan='3' class='HJ_CP_WLM'>高于理论价格10%理由:  <span style='text-align:left'>{0}</span></td>", BN);
                        break;
                    }
                }
            }
            html.AppendLine("</tr>");
            // 添加表格结束标签  
            html.AppendLine("</table>");

            return html.ToString();
        }



        #region 导出文件
        [HttpPost]
        public ActionResult Wenjian(string bian)
        {
            //获取bom 
            var App = db.Applications.Where(s => s.AP_bian == bian).FirstOrDefault();
            if (App != null)
            {
                try
                {
                    var HN = App == null ? "" : App.App_BanB;
                    var bom = db.BOMini.Where(s => s.BOM2_bian == bian && s.BOM2_Zhuang == HN).ToList();
                    //工艺记录

                    //保存物料
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    using (ExcelPackage excel = new ExcelPackage())
                    {
                        // 添加工作表
                        var worksheet = excel.Workbook.Worksheets.Add("项目物料信息");
                        // 写入数据
                        worksheet.Cells[1, 1].Value = "层级";
                        worksheet.Cells[1, 2].Value = "物料编码";
                        worksheet.Cells[1, 3].Value = "物料名称";
                        worksheet.Cells[1, 4].Value = "规格";
                        worksheet.Cells[1, 5].Value = "年用量";
                        worksheet.Cells[1, 6].Value = "BOM用量";
                        worksheet.Cells[1, 7].Value = "计量单位";
                        worksheet.Cells[1, 8].Value = "申请类型";
                        worksheet.Cells[1, 9].Value = "备注";
                        worksheet.Cells[1, 10].Value = "原材料";
                        worksheet.Cells[1, 11].Value = "一级类别";
                        worksheet.Cells[1, 12].Value = "二级类别";
                        worksheet.Cells[1, 13].Value = "最小起订量";
                        int i = 2;
                        foreach (BOMini des in bom)
                        {
                            int index = 1;
                            worksheet.Cells[i, index].Value = des.BOM2_chen;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_liao;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_wuLiu;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_Guige;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_Nian;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_Yong;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_fenzi;
                            index++;
                            worksheet.Cells[i, index].Value = des.BOM2_Lei;
                            index++;
                            worksheet.Cells[i, index].Value = des.Formation.FM_ms;
                            index++;
                            worksheet.Cells[i, index].Value = des.Formation.FM_ycl;
                            index++;
                            worksheet.Cells[i, index].Value = des.Formation.FM_yj;
                            index++;
                            worksheet.Cells[i, index].Value = des.Formation.FM_ej;
                            index++;
                            worksheet.Cells[i, index].Value = des.Formation.FM_Jieti;
                            i++;
                        }
                        worksheet.Cells["A:Z"].AutoFitColumns();
                        var worksheet1 = excel.Workbook.Worksheets.Add("成本明细");
                        worksheet1.Cells[1, 1].Value = "物料编码";
                        worksheet1.Cells[1, 2].Value = "物料名称";
                        worksheet1.Cells[1, 3].Value = "实际规格";
                        worksheet1.Cells[1, 4].Value = "规格";
                        worksheet1.Cells[1, 5].Value = "计算面积";
                        worksheet1.Cells[1, 6].Value = "材质";
                        worksheet1.Cells[1, 7].Value = "工艺";
                        worksheet1.Cells[1, 8].Value = "辅料";
                        worksheet1.Cells[1, 9].Value = "成本价";
                        i = 2;
                        foreach (var item in bom)
                        {
                            var id = item.BOM2_id;
                            var crea = db.ProcessRecord.Where(s => s.wl_liao == id.ToString()).FirstOrDefault();
                            int index = 1;
                            worksheet1.Cells[i, index].Value = item.BOM2_liao;
                            index++;
                            worksheet1.Cells[i, index].Value = item.BOM2_wuLiu;
                            index++;
                            worksheet1.Cells[i, index].Value = crea == null ? "" : crea.wl_gui;
                            index++;
                            worksheet1.Cells[i, index].Value = crea == null ? "" : item.BOM2_Guige;
                            index++;
                            var mianji = crea == null ? 0 : crea.wl_gui == null ? 0 : double.Parse(crea.wl_gui.Split('*')[0]) * double.Parse(crea.wl_gui.Split('*')[1]);
                            worksheet1.Cells[i, index].Value = mianji;
                            var minj = "";
                            if (crea != null)
                            {
                                var cl = db.CraftMaterials.Join(db.parice, cm => cm.cl_id, pr => pr.PA_ID, (cm, pr) => new { pr.PA_KZ, cm.prr_id }).Where(s => s.prr_id == crea.prr_id).ToList();
                                for (int j = 0; j < cl.Count(); j++)
                                {
                                    if (j == (cl.Count() - 1))
                                    {
                                        minj += cl[j].PA_KZ;
                                    }
                                    else
                                    {
                                        minj += cl[j].PA_KZ + "*";
                                    }
                                }
                            }
                            index++;
                            worksheet1.Cells[i, index].Value = minj;
                            index++;
                            var fnei = "";
                            if (crea != null)
                            {
                                var LM = crea == null ? null : db.ProcessFlow.Join(db.libray, cm => cm.gy_id, pr => pr.LB_ID, (cm, pr) => new { pr.LB_fne, cm.pfw_gg, cm.pfw_jia, cm.prr_id }).Where(s => s.prr_id == crea.prr_id).ToList();
                                for (int j = 0; j < LM.Count(); j++)
                                {
                                    fnei += LM[j].LB_fne + ":" + LM[j].pfw_gg;
                                }
                            }
                            worksheet1.Cells[i, index].Value = fnei;
                            index++;
                            worksheet1.Cells[i, index].Value = null;
                            index++;
                            var OP = db.operational.Where(s => s.OP_ID == item.BOM2_Gong).FirstOrDefault();
                            var sji = OP == null ? 0 : OP.OP_price;
                            worksheet1.Cells[i, index].Value = sji;
                            i++;
                        }
                        worksheet1.Cells["A:Z"].AutoFitColumns();
                        string path = "";
                        path = Server.MapPath("~/Files/");
                        string Name = "物料BOM成本明细.xlsx";
                        // 确保目录存在  
                        Directory.CreateDirectory(path);

                        // 生成唯一的文件名（这里只是简单示例，你可能需要更复杂的唯一性逻辑）  
                        string fileName = Path.GetFileNameWithoutExtension(Name) + "_" + Guid.NewGuid() + Path.GetExtension(Name);

                        // 保存文件到服务器  
                        string filePath = Path.Combine(path, fileName);
                        excel.SaveAs(filePath);
                        return Json(filePath);
                    }
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            else
            {
                return Json("无工艺或BOM");
            }

            return View();
        }
        #endregion

        public ActionResult GysH(string bian = "", int stantes = 0, int id = 0)
        {
            ViewBag.Liao = db.buty2.ToList();
            ViewBag.temp21 = db.buty3.ToList();
            Session["GYSbian"] = bian;
            return View();
        }
    }
}